package lib.common;

import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.net.NetworkInterface;
import java.net.InetAddress;
import java.util.Collections;

import io.github.cdimascio.dotenv.Dotenv;

public class Common {
    private static String _resolveEnv(Dotenv dotenv, String name) {
        String v = dotenv.get(name);
        if (v == null)
            return null;
        Matcher p = Pattern.compile("\\$\\{([^}]*)\\}").matcher(v);

        String ret = v;
        while (p.find()) {
            String subVarValue = _resolveEnv(dotenv, p.group(1));
            if (subVarValue == null)
                return null;
            ret = v.replace(p.group(0), subVarValue);
        }
        return ret ;
    }

    public static String resolveEnv(Dotenv dotenv, String name, String defaultValue) {
        String resolveValue = _resolveEnv(dotenv, name);
        return resolveValue != null ? resolveValue : defaultValue;
    }
    public static String resolveMyIp(String nodes) throws Exception {
        for (NetworkInterface ni : Collections.list(NetworkInterface.getNetworkInterfaces())) {
            for (InetAddress addr : Collections.list(ni.getInetAddresses())) {
                String currentIp = addr.getHostAddress();
                if (nodes.contains(currentIp)) {
                    return currentIp;
                }
            }
        }
        return null;
    }
}
